package com.tangcco.controller;

import com.tangcco.biz.UserBiz;
import com.tangcco.pojo.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/user")
public class UserController {
	@Resource
	private UserBiz userBiz;

	@ResponseBody
	@RequestMapping("/login")
	public Object login(String loginPhone, String loginPwd, HttpSession session) {
		User user = userBiz.login(loginPhone,loginPwd);
		Map<String,String> map = new HashMap<>();
		if(user != null){
			session.setAttribute("user",user);
			map.put("loginResult","success");
		}else{
			map.put("loginResult","lose");
		}
		return map;
	}

	@ResponseBody
	@RequestMapping("/getCode")
	public Object getCode(){
 		String str = "ABCEFGHJKLMNPQRSTWXYZ123456789";
 		String code = "";
		for (int i = 0; i < 4; i++) {
			int index = (int) Math.floor((Math.random() * str.length()));
			code += str.substring(index,index+1);
		}
		if(code.length() == 4){
			return code;
		}
		return null;
	}

	@ResponseBody
	@RequestMapping("/register")
	public Object register(String phone,String password,String code,HttpSession session) {
		Map<String,String> map = new HashMap<>();
		String oldCode = (String) session.getAttribute("code");
		User user = null;
		if(oldCode.equals(code)){
			int result = userBiz.register(phone,password);
			if(result > 0){
				user = userBiz.login(phone,password);
				session.setAttribute("user",user);
				map.put("resResult","success");
			}
			return map;
		}else{
			map.put("resResult","lose");
			return map;
		}
	}

	//发送手机验证码
	@ResponseBody
	@RequestMapping("/sendMsg")
	public String sendMsg(String phone,HttpSession session){
		String codeStr = String.valueOf(Math.random());
		String code = codeStr.substring(codeStr.length() - 4,codeStr.length());
		session.setAttribute("code",code);
		return userBiz.checkPhone(phone,code);
	}

	//退出(清空session)
	@RequestMapping("/loginOut")
	public String loginOut(HttpSession session){
		session.removeAttribute("user");
		session.invalidate();
		return "redirect:/jsp/index.jsp";
	}
}
